package com.ysx.oa.role.service.impl;

import com.ysx.oa.clazz.bean.ClazzStudentTeacherBean;
import com.ysx.oa.clazz.dao.ClazzStudentTeacherDao;
import com.ysx.oa.role.bean.UserRoleBean;
import com.ysx.oa.role.dao.UserRoleDao;
import com.ysx.oa.role.dto.UserRoleDTO;
import com.ysx.oa.role.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: 王伟雄
 * @Date: 2021/11/20 16:10
 */
@Service
public class UserRoleServiceImpl implements UserRoleService {
    @Autowired
    private UserRoleDao dao;

    @Autowired
    private ClazzStudentTeacherDao clazzStudentTeacherDao;


    @Override
    public Integer add(UserRoleBean userRoleBean) {
        UserRoleBean bean=new UserRoleBean();
        bean.setRoleId(userRoleBean.getRoleId());
        bean.setUserId(userRoleBean.getUserId());

        if(dao.select(bean).size()>0){
            return 0;
        }
        Integer rs = dao.insert(userRoleBean);
        return rs;
    }

    @Override
    public Integer update(UserRoleBean userRoleBean) {
        Integer rs = dao.updateByUserIdRoleId(userRoleBean);
        return rs;
    }

    @Override
    public List<UserRoleBean> findSelected(UserRoleBean userRoleBean) {
        List<UserRoleBean> rs = dao.findSelected(userRoleBean);
        return rs;
    }

    @Override
    public List<UserRoleBean> findAll() {
        List<UserRoleBean> rs = dao.findAll();
        return rs;
    }

    @Override
    public List<UserRoleBean> findAllAllocated() {
        List<UserRoleBean> rs = dao.findAllAllocated();
        return rs;
    }

    @Override
    public Integer delete(UserRoleDTO userRoleDto) {
        List<Integer> ids = userRoleDto.getIds();
        for(Integer id:ids){
            // 通过集合重点id查到用户id
            UserRoleBean userRoleBean=new UserRoleBean();
            userRoleBean.setId(id);
            Integer userId = dao.selectOne(userRoleBean).getUserId();
            ClazzStudentTeacherBean clazzStudentTeacherBean=new ClazzStudentTeacherBean();
            clazzStudentTeacherBean.setUserId(userId);
            // 通过用户id查到用户有没有分配班级，如果没有则可以删除
            List<ClazzStudentTeacherBean> clazzStudentTeacherBeans = clazzStudentTeacherDao.select(clazzStudentTeacherBean);
            if(clazzStudentTeacherBeans.size()>0){
                return 0;
            }
        }
        return  dao.deleteUserRole(ids);
    }
}
